package com.lht.femalecat.netty.stick;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.Date;

/**
 * @Author:骆宏图
 * @CreateDate: 14:16 2018/7/27.
 * @Description:
 * @Modified By:
 */
public class TimeServer {

    public static void main(String[] args){
        EventLoopGroup  accept= new NioEventLoopGroup();
        EventLoopGroup  proeccess=new NioEventLoopGroup();

        ServerBootstrap b=new ServerBootstrap();


        try {
            b.group(accept,proeccess).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,1024);
            b.childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
//                    socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
//                    socketChannel.pipeline().addLast(new StringDecoder());
                    socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            ctx.close();
                        }


                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            ByteBuf buf=(ByteBuf)msg;
                            byte[] bytes=new byte[buf.readableBytes()];
                            buf.readBytes(bytes);

                            String body=new String(bytes,"UTF-8").substring(0,bytes.length-System.getProperty("line.separator").length());
                            System.out.println("The Time body :"+ body);

                            String currentTime="Query Time Order".equalsIgnoreCase(body)?new Date(System.currentTimeMillis()).toString():"Bad Order";
                            currentTime+=System.getProperty("line.separator");
                            ByteBuf res= Unpooled.copiedBuffer(currentTime.getBytes());
                            ctx.writeAndFlush(res);
                        }
                        @Override
                        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                            ctx.flush();
                        }
                    });
                }
            });
            ChannelFuture f=b.bind(8080).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            accept.shutdownGracefully();
            proeccess.shutdownGracefully();
        }

    }
}
